package com.zhengb.algorithmdemo.basic.sort;

import java.util.Arrays;

/**
 * Created by zhengbo on 2020/2/25.
 */
public class BubbleSort {

    /**
     * 冒泡排序 一般实现 复杂度为O(n2)
     *
     * @param array
     */
    public static void bubbleSort(int[] array) {

        for (int pass = array.length - 1; pass >= 0; pass--) {
            for (int i = 0; i < pass - 1; i++) {
                if (array[i] > array[i + 1]) {
                    int temp = array[i];
                    array[i] = array[i + 1];
                    array[i + 1] = temp;
                }
            }
        }
    }


    /**
     * 改进版本冒泡排序 时间复杂度O(N)
     *
     * @param array
     */
    public static void bubbleSortImproved(int[] array) {
        int pass, i, temp, swapped = 1;

        for (pass = array.length - 1; pass > 0 && swapped > 0; pass--) {
            swapped = 0;

            for (i = 0; i < pass - 1; i++) {
                if (array[i] > array[i + 1]) {
                    temp = array[i];
                    array[i] = array[i + 1];
                    array[i + 1] = temp;

                    swapped = 1;
                }
            }
        }
    }


    public static void main(String[] args) {

        int[] array = new int[]{3, 5, 7, 4, 2, 9, 10};

        bubbleSortImproved(array);

        System.out.println(Arrays.toString(array));

    }
}
